/**
 * grid组件
 * 
 * 数据分页组件，通过ajax请求资源，返回分页数据，在table中进行展示。
 * 主要参数：
 * server  ：http请求方法
 * currentPageIndex ：当前页码
 * pageSize  ：每页显示条数
 * 
 * 
 */




(function($) {
	
	
	
	
	/**
	 * 通过Params发送请求
	 * @param params grid参数配置
	 * @param successCallback success时候回调函数
	 * @param failCallback error时候回调函数
	 */

	
	$.fn.mobileGrid=function(params){
		return this.each(function(index,dom){
			var $el=$(dom),settings;
			var tableId =$el.attr("id");
			if(!tableId){
				console.log("缺少ID参数。");
				return false;
			}
			var gridType=$el.attr("data-role");
			$("#"+tableId).addClass(" ui-mobile-grid");
			if($("#"+tableId).attr("data-settings"))
				var grid_set=$("#"+tableId).attr("data-settings");
			settings=eval("("+grid_set+")");
			var options=$.extend({pageSize:10,currentPageIndex:1},settings,params);
		
			
			if(options.autoload==undefined||options.autoload){
				if(gridType=="gridtable"){
					$("div.pagebar.auto-pagebar",$("#"+tableId)).append(gridOptions.gridtableBarTempl);
					pagebar(tableId);
				}
				if(gridType=="gridscrolllist"){
					    createGridShowPatch(tableId,options);
					   pagebar2(tableId);
				}				
			    $el.search(options);
		
			}
			$el.data("mobileGrid",options);

		});
	};
	
	/**
	 * 查询方法接口
	 * 带参查询
	 * 格式："{server:methodName,id:2,name:'name'}"
	 */
	$.fn.search = function(params,successCallback,failCallback) {
		var tableId = $(this).attr("id");
		var gridType=$("#"+tableId).attr("data-role");
		if(params){
			//currentPageIndex默认为1
			var currentPageIndex = params["currentPageIndex"];
			if(!currentPageIndex || currentPageIndex==null){
				params = $.extend($("#"+tableId).data("mobileGrid"),params, {currentPageIndex:1});
			}
			$(this).params(params);
		}
		
		var actionParams = params;
		var action = actionParams["server"];
		var paramsStr = "";
		var autoload = actionParams["autoload"];
		if(autoload==undefined || autoload){
			if(gridType=='gridtable')
			   showProgressBar(tableId);
			 Newtouch.Ajax
			 	.navigationSendParams(actionParams, action, function(data){
				if(gridType=='gridtable'){
					hideProgressBar(tableId);
				   _addJSONData1(tableId, data);
				}
				if(gridType=='gridscrolllist')
				   _addJSONData2(tableId, data);
				$("#"+tableId).data("mobileGrid",actionParams);
				var message = $("div.message",$("#"+tableId));
				if(message){
					message.html("");
				}
				
				if(successCallback && typeof(successCallback)=="function"){
					successCallback(data);
				}
				
			}, function(error){
				hideProgressBar(tableId);
				
				var message = $("div.message",$("#"+tableId));
				if(message){
					message.html(error);
				}
				
				if(failCallback && typeof(failCallback)=="function"){
					failCallback(error);
				}
			}, false);
		}
	};
	
    //增加本地数据库（websqlite）支持
	/**
	 * params.localData格式按照page 分页返回类型配置{"pageSize":"1","currentPageIndex:"1","totalPage:"2",items:[]}
	 * 必要的参数：pageSize,currentPageIndex,totalPage,items数组
	 */
	$.fn.mobileLocalGrid=function(params){
		return this.each(function(index,dom){
			var $el=$(dom),settings;
			var tableId =$el.attr("id");
			var gridType=$el.attr("data-role");
			$("#"+tableId).addClass(" ui-mobile-grid");
			if($("#"+tableId).attr("data-settings"))
				var grid_set=$("#"+tableId).attr("data-settings");
			settings=eval("("+grid_set+")");
			var options=$.extend({},settings,params);
			if(gridType=="gridtable"){
				  _addJSONData1(tableId,options.localData);
			}
			if(gridType=="gridscrolllist"){
				   _addJSONData2(tableId, options.localData);
			}	
				
			$el.data("mobileGrid",options);

		});
	};
	
	//加载下一页
	$.fn.loadNextPage=function(){
		
		   var tableId=$(this).attr("id");
		   $(".nextPage",$("[data-target-grid='"+tableId+"'] table")).trigger("click");
	}
	//加载上一页
	$.fn.loadPreviPage=function(){
		
		   var tableId=$(this).attr("id");
		   $(".previousPage",$("[data-target-grid='"+tableId+"'] table")).trigger("click");
	}
	
	//配置参数
	$.fn.params = function(params){
		var tableId = $(this).attr("id");
		var actionParams = $("#"+tableId).data("mobileGrid");
		if(params==undefined){
			return actionParams;
		}else{
			var actionParams = $.extend(actionParams, params);
			$("#"+tableId).data("mobileGrid",actionParams);
		}
		
	};
	
	//获取当前页数
	$.fn.currentPage = function(){
		var tableId = $(this).attr("id");
		var actionParams = $("#"+tableId).data("mobileGrid");
		return actionParams["currentPageIndex"];
	};
	
	//总记录数
	$.fn.totalCount = function(){
		var tableId = $(this).attr("id");
		var actionParams = $("#"+tableId).data("mobileGrid");
		return actionParams["totalCount"];
		
	};
	
	
	//获取某行数据
	$.fn.record = function(rowId){
		var tableId = $(this).attr("id");
		var record = null;
		var gridType=$("#"+tableId).attr("data-role");
		if(gridType=="gridtable"){
				$("#"+tableId+" tbody tr:not(.grid_tr_templete)").each(function(index, dom){
					if(index==rowId){
						record = $.data(dom,"record");
						return false;
					}
					return true;
				});
			
		}
		if(gridType=="gridscrolllist"){
			 	$("[data-target-grid='"+tableId+"'] table tbody tr").each(function(index, dom){
					if(index==rowId){
						record = $.data(dom,"record");
						return false;
					}
					return true;
				});
		}
		return record;
	};
	
	//获取checkbox，radio选择的行数据
	$.fn.selectedRecords = function(){
		var tableId = $(this).attr("id");
		var records = new Array();
		var gridType=$("#"+tableId).attr("data-role");
		if(gridType=="gridtable"){
			$("#"+tableId+" tbody tr:not(.grid_tr_templete)").each(function(index, dom){
				var selector = $(".grid_tr_selector", $(dom)).get(0);
				if(selector){
					var value = $.data(dom,"record");
					var checked = $(selector).hasClass("checked");
					if(checked && value!=null)
						records.push(value);
				}
			});
		
		}
		if(gridType=="gridscrolllist"){
			$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)").each(function(index, dom){
				var selector = $(".grid_tr_selector", $(dom)).get(0);
				if(selector){
					var value = $.data(dom,"record");
					var checked = $(selector).hasClass("checked");
					if(checked && value!=null)
						records.push(value);
				}
			});
			
		}
		
		return records;
	};
	//清除信息
	$.fn.clearMessage = function(){
		var message = $("div.message",$("#"+tableId));
		if(message) message.html("");
	};
	
	
		

//工具栏模板
var gridOptions={
		gridlistBarTempl:'<div style="display:none;">'+
							'<span class="totalCount" > </span>'+
							'<span class="currentPageIndex"> </span>/<span class="totalPage"> </span>'+
							'</div>'+
							'<div class="row-fluid" style="text-align:center;">'+
							'<button type="button" class="nextPage btn" >下一页</button>'+
							'</div>'+
							'<input type="text" class="pageSize" style="display:none;"></input>'+
							'</div>',
		 gridtableBarTempl:'<div style="display:none;">'+
							'<span class="totalCount" > </span>'+
							'<span class="currentPageIndex"> </span>/<span class="totalPage"> </span>'+
							'</div>'+
							'<div class="row-fluid" style="text-align:center;">'+
							  '<div class="btn-group" >'+
									'<button type="button" class="firstPage btn hidden-phone">首页</button>'+
									'<button type="button" class="previousPage btn">上一页</button>'+
									'<select class="currentPage inputW20"></select>'+
									'<button type="button" class="nextPage btn">下一页</button>'+
									'<button type="button" class="lastPage btn hidden-phone">尾页</button>'+
							  '</div>'+
							'</div>'+
							'<input type="text" class="pageSize" style="display:none;"></input>'
		
};


var _addJSONData1 = function(tableId, data){
	var items = data.items;
	var currentPageIndex = parseInt(data.currentPageIndex);
	var lastPageIndex =  parseInt(data.lastPageIndex);
	var nextPageIndex =  parseInt(data.nextPageIndex);
	var pageSize =  parseInt(data.pageSize);
	var previousPageIndex =  parseInt(data.previousPageIndex);
	var totalCount =  parseInt(data.totalCount);
	var totalPage =  parseInt(data.totalPage);
	var settings={'totalCount':totalCount,'totalPage':totalPage};
	$("#"+tableId).params(settings);
	var span_totalCount = $(".totalCount",$("#"+tableId));
	$(span_totalCount).html(totalCount);
	var span_currentPageIndex = $(".currentPageIndex",$("#"+tableId));
	$(span_currentPageIndex).html(currentPageIndex);
	var span_totalPage = $(".totalPage",$("#"+tableId));
	$(span_totalPage).html(totalPage);
	var input_currentPage = $(".currentPage",$("#"+tableId));
	$(input_currentPage).val(currentPageIndex);
	var input_pageSize = $(".pageSize",$("#"+tableId));
	$(input_pageSize).val(pageSize);
	
	
	
	var pagebar = $("div.pagebar",$("#"+tableId));
	if(totalPage>1){
		pagebar.show();
		if(pagebar.hasClass("auto-pagebar")){
			var optionsSelectHtml="<option value='' ></option>";
			for(var i=1;i<=totalPage;i++){
				if(i==currentPageIndex){
					optionsSelectHtml+="<option value='"+i+"' selected>"+i+"</option>";
				}
				else{
					optionsSelectHtml+="<option value='"+i+"'>"+i+"</option>";
				}
			}
			$("select.currentPage",pagebar).html($(optionsSelectHtml));
			if($("select.currentPage",pagebar).closest(".ui-select").length==0){
				$("select.currentPage",pagebar).selectpicker();
			}else{
				$("select.currentPage",pagebar).closest(".ui-select").find('.filter-option').html($("select.currentPage",pagebar).selectpicker("val"));
			}
		}
	}else if(totalPage<=1){
		pagebar.hide();
		
	}
	if(pagebar){	
		if(currentPageIndex==1){
			$(".firstPage",pagebar).removeAttr("href").attr("disabled","disabled");
			$(".previousPage",pagebar).removeAttr("href").attr("disabled","disabled");
		}else{
			$(".firstPage",pagebar).attr("href","javascript:void(0)").removeAttr("disabled");
			$(".previousPage",pagebar).attr("href","javascript:void(0)").removeAttr("disabled");
		}
		if(currentPageIndex>=totalPage){
			$(".nextPage",pagebar).removeAttr("href").attr("disabled","disabled");
			$(".lastPage",pagebar).removeAttr("href").attr("disabled","disabled");
		}else{
			$(".nextPage",pagebar).attr("href","javascript:void(0)").removeAttr("disabled");
			$(".lastPage",pagebar).attr("href","javascript:void(0)").removeAttr("disabled");
		}
	}
	
	$("#"+tableId+" tbody tr:not(.grid_tr_templete)").each(function(index, dom){
		$(dom).remove();
	});
	for(var i=0;i<items.length;i++){
		$("#"+tableId+" tbody tr.grid_tr_templete").each(function(index, dom){
			var o = items[i];
			if(o){
				var new_tr = $(dom).clone();
				$(new_tr).removeClass("grid_tr_templete");
				$(new_tr).css("display","");
				$.data($(new_tr).get(0),"record",o);
				$("td",$(new_tr)).each(function(j, d){
					var field = $("#"+tableId+" thead tr th:eq("+j+")").attr("field");
					if(field!=undefined && field!=""){
						$(d).attr("title",o[field]);
						$(d).append(o[field]);
					}
				});
				$("#"+tableId+" tbody").append(new_tr);
			}
		});
	}
	
	sorter();
	selector(tableId);
	setIndex(tableId);
	formatter(tableId);
	
};


var _addJSONData2 = function(tableId, data){
	var items = data.items;
	var currentPageIndex = parseInt(data.currentPageIndex);
	var lastPageIndex =  parseInt(data.lastPageIndex);
	var nextPageIndex =  parseInt(data.nextPageIndex);
	var pageSize =  parseInt(data.pageSize);
	var previousPageIndex =  parseInt(data.previousPageIndex);
	var totalCount =  parseInt(data.totalCount);
	var totalPage =  parseInt(data.totalPage);
	var settings={'totalCount':totalCount,'totalPage':totalPage};
	$("#"+tableId).params(settings);
	var span_totalCount = $(".totalCount",$("[data-target-grid='"+tableId+"']"));
	$(span_totalCount).html(totalCount);
	var span_currentPageIndex = $(".currentPageIndex",$("[data-target-grid='"+tableId+"']"));
	$(span_currentPageIndex).html(currentPageIndex);
	var span_totalPage = $(".totalPage",$("[data-target-grid='"+tableId+"']"));
	$(span_totalPage).html(totalPage);
	var input_currentPage = $(".currentPage",$("[data-target-grid='"+tableId+"']"));
	$(input_currentPage).val(currentPageIndex);
	var input_pageSize = $(".pageSize",$("[data-target-grid='"+tableId+"']"));
	$(input_pageSize).val(pageSize);
	
	var pagebar = $("div.pagebar",$("[data-target-grid='"+tableId+"']"));
	if(totalPage>1){
		pagebar.show();
	}else if(totalPage<=1){
		pagebar.hide();
		
	}
	if(pagebar){	
		
		if(currentPageIndex>=totalPage){
			$(".nextPage",pagebar).removeAttr("href").attr("disabled","disabled");
			
		}else{
			$(".nextPage",pagebar).attr("href","javascript:void(0)").removeAttr("disabled");
			
		}
	}

	for(var i=0;i<items.length;i++){
		$("#"+tableId+" tbody tr.grid_tr_templete").each(function(index, dom){
			
			var o = items[i];
			if(o){
				var new_tr = $(dom).clone();
				$(new_tr).removeClass("grid_tr_templete");
				$(new_tr).css("display","");
				$.data($(new_tr).get(0),"record",o);
				$("td",$(new_tr)).each(function(j, d){
					
					var field = $("#"+tableId+" thead tr th:eq("+j+")").attr("field");
					if(field!=undefined && field!=""){
						$(d).attr("title",o[field]);
						$(d).append(o[field]);
					}
				});
				$("[data-target-grid='"+tableId+"'] table > tbody ").append(new_tr);
			}
		});
	}
	
	sorter2(tableId);
	selector2(tableId);
	setIndex2(tableId);
	formatter2(tableId);

};	
var sorter = function(){
	//排序功能实现
	var headers = "";
	var sortList = "";
	var formatterList = "";
	$("table.tablesorter thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		if(th_class&&th_class.indexOf("sortable")==-1){
			headers = headers +index +":{sorter: false},"
		}
		
		if(th_class&&th_class.indexOf("sortable-desc")>=0){
			sortList = sortList +"["+index+",1"+"],";
		}else if(th_class&&th_class.indexOf("sortable-asc")>=0){
			sortList = sortList +"["+index+",0"+"],";
		}
	});
	
	var headers_object = eval("({"+headers.substring(0,headers.length-1)+"})");
	var sortList_object = eval("(["+sortList.substring(0,sortList.length-1)+"])");
	$("table.tablesorter").tablesorter({
		headers:headers_object,
		sortList:sortList_object
	});
}

var selector = function(tableId){
	//多选框实现
	$("#"+tableId+" thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		var isCheckbox = /(.*\\s)?[cC][hH][eE][cC][kK][bB][oO][xX](\\s.*)?/.test(th_class);
		var isRadio = /(.*\\s)?[rR][aA][dD][iI][oO](\\s.*)?/.test(th_class);
		
		if(isCheckbox){
			$(this).attr("align","center");
			
			var str="<label id='"+tableId+"_th_checkbox' class='checkbox grid_tr_selector'>"+
			'<span class="icons"><span class="first-icon fui-checkbox-unchecked"></span><span class="second-icon fui-checkbox-checked"></span></span>'+
		    '</label>';
			
			$(this).html(str);
//			$(this).html("<input id='"+tableId+"_th_checkbox' type='checkbox' class='grid_th_selector'>");
			$("#"+tableId+" tbody tr:not(.grid_tr_templete)").each(function(i, d){
				var td_d = $("td:eq("+index+")", d);
				$(td_d).attr("align","center");
//				$(td_d).html("<input type='checkbox' name='checkbox' class='grid_tr_selector'>");
				$(td_d).html(str);
			});
			
			
			//全选状态
			$(".grid_tr_selector",$("#"+tableId+" thead tr")).each(function(index,dom){
				   $(dom).bind("click",function(){
				      var checked=$(this).hasClass("checked");
				      if(checked){
				    	  $(this).removeClass("checked");
				    	  $(".grid_tr_selector",$("#"+tableId+" tbody tr:not(.grid_tr_templete)")).removeClass("checked");
				      }
				      else{
				    	  $(this).addClass("checked");
				    	  $(".grid_tr_selector",$("#"+tableId+" tbody tr:not(.grid_tr_templete)")).addClass("checked");
				      }
				   });
				
			});
			
			//单元行选中状态
			$(".grid_tr_selector",$("#"+tableId+" tbody tr:not(.grid_tr_templete)")).each(function(index,dom){
				   $(dom).bind("click",function(){
				      var checked=$(this).hasClass("checked");
				      if(checked){
				    	  $(this).removeClass("checked");
				      }
				      else{
				    	  $(this).addClass("checked");
				      }
				   });
				
			});
			
		}
		else if(isRadio){
			
			var str="<label id='"+tableId+"_th_checkbox' class='radio grid_tr_selector'>"+
			'<span class="icons"><span class="first-icon fui-radio-unchecked"></span><span class="second-icon fui-radio-checked"></span></span>'+
		    '</label>';
			$("#"+tableId+" tbody tr:not(.grid_tr_templete)").each(function(i, d){
				var td_d = $("td:eq("+index+")", d);
				$(td_d).attr("align","center");
//				$(td_d).html("<input type='radio' name='radio' class='grid_tr_selector'>");
				$(td_d).html(str);
			});
			
			//单元行选中状态
			$(".grid_tr_selector",$("#"+tableId+" tbody tr:not(.grid_tr_templete)")).each(function(index,dom){
				   $(dom).bind("click",function(){
				      var checked=$(this).hasClass("checked");
				      if(checked){
//				    	  $(this).removeClass("checked");
				      }
				      else{
				    	  $(".grid_tr_selector",$("#"+tableId+" tbody tr:not(.grid_tr_templete)")).removeClass("checked");
				    	  $(this).addClass("checked");
				      }
				   });
				
			});
		}
	});
	
}


var selector2 = function(tableId){
	//多选框实现
	$("#"+tableId+" thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		var isCheckbox = /(.*\\s)?[cC][hH][eE][cC][kK][bB][oO][xX](\\s.*)?/.test(th_class);
		var isRadio = /(.*\\s)?[rR][aA][dD][iI][oO](\\s.*)?/.test(th_class);
		
		if(isCheckbox){
			$(this).attr("align","center");
			
			var str="<label id='"+tableId+"_th_checkbox' class='checkbox grid_tr_selector'>"+
			'<span class="icons"><span class="first-icon fui-checkbox-unchecked"></span><span class="second-icon fui-checkbox-checked"></span></span>'+
		    '</label>';
			
			$(this).html(str);
//			$(this).html("<input id='"+tableId+"_th_checkbox' type='checkbox' class='grid_th_selector'>");
			$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)").each(function(i, d){
				var td_d = $("td:eq("+index+")", d);
				$(td_d).attr("align","center");
//				$(td_d).html("<input type='checkbox' name='checkbox' class='grid_tr_selector'>");
				$(td_d).html(str);
			});
			
			
			//全选状态
			$(".grid_tr_selector",$("#"+tableId+" thead tr")).each(function(index,dom){
				   $(dom).bind("click",function(){
				      var checked=$(this).hasClass("checked");
				      if(checked){
				    	  $(this).removeClass("checked");
				    	  $(".grid_tr_selector",$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)")).removeClass("checked");
				      }
				      else{
				    	  $(this).addClass("checked");
				    	  $(".grid_tr_selector",$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)")).addClass("checked");
				      }
				   });
				
			});
			
			//单元行选中状态
			$(".grid_tr_selector",$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)")).each(function(index,dom){
				   $(dom).bind("click",function(){
				      var checked=$(this).hasClass("checked");
				      if(checked){
				    	  $(this).removeClass("checked");
				      }
				      else{
				    	  $(this).addClass("checked");
				      }
				   });
				
			});
			
		}
		else if(isRadio){
			
			var str="<label id='"+tableId+"_th_checkbox' class='radio grid_tr_selector'>"+
			'<span class="icons"><span class="first-icon fui-radio-unchecked"></span><span class="second-icon fui-radio-checked"></span></span>'+
		    '</label>';
			$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)").each(function(i, d){
				var td_d = $("td:eq("+index+")", d);
				$(td_d).attr("align","center");
//				$(td_d).html("<input type='radio' name='radio' class='grid_tr_selector'>");
				$(td_d).html(str);
			});
			
			//单元行选中状态
			$(".grid_tr_selector",$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)")).each(function(index,dom){
				   $(dom).bind("click",function(){
				      var checked=$(this).hasClass("checked");
				      if(checked){
//				    	  $(this).removeClass("checked");
				      }
				      else{
				    	  $(".grid_tr_selector",$("[data-target-grid='"+tableId+"'] table tbody tr:not(.grid_tr_templete)")).removeClass("checked");
				    	  $(this).addClass("checked");
				      }
				   });
				
			});
		}
	});
	
}

var sorter2 = function(tableId){
	//排序功能实现
	var headers = "";
	var sortList = "";
	var formatterList = "";
	$("[data-target-grid='"+tableId+"'] table.tablesorter thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		if(th_class&&th_class.indexOf("sortable")==-1){
			headers = headers +index +":{sorter: false},"
		}
		
		if(th_class&&th_class.indexOf("sortable-desc")>=0){
			sortList = sortList +"["+index+",1"+"],";
		}else if(th_class&&th_class.indexOf("sortable-asc")>=0){
			sortList = sortList +"["+index+",0"+"],";
		}
	});
	
	var headers_object = eval("({"+headers.substring(0,headers.length-1)+"})");
	var sortList_object = eval("(["+sortList.substring(0,sortList.length-1)+"])");
	$("[data-target-grid='"+tableId+"'] table.tablesorter").tablesorter({
		headers:headers_object,
		sortList:sortList_object
	});
}
var setIndex = function(tableId){
	var currentPageIndex = parseInt($("#"+tableId).currentPage());
	var pageSize = parseInt($("input.pageSize",$("#"+tableId)).val());
    
	//设置序号功能实现
	$("#"+tableId+" thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		var result = /(.*\\s)?[iI][nN][dD][eE][xX](\\s.*)?/.test(th_class);
		
		if(result){
			$("#"+tableId+" tbody tr:not(.grid_tr_templete)").each(function(i, d){
				var td_d = $("td:eq("+index+")", d);
				
				td_d.children().length>0?td_d.children().after(pageSize*(currentPageIndex-1)+i+1):td_d.html(pageSize*(currentPageIndex-1)+i+1);
			});
		}
	});
}

var setIndex2 = function(tableId){
	var currentPageIndex = parseInt($("#"+tableId).currentPage());
	var pageSize = parseInt($("input.pageSize",$("[data-target-grid='"+tableId+"'] table ")).val());
    
	//设置序号功能实现
	$("#"+tableId+" thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		var result = /(.*\\s)?[iI][nN][dD][eE][xX](\\s.*)?/.test(th_class);
		
		if(result){
			$("[data-target-grid='"+tableId+"'] table tbody tr").each(function(i, d){
				var td_d = $("td:eq("+index+")",  d);
				td_d.html(i+1);
			});
		}
	});
}

var formatter = function(tableId){
	//格式化功能实现
	$("#"+tableId+" thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		//var result = /(.*\\s)?[fF][oO][rR][mM][aA][tT][tT][eE][rR]-.+(\\s.*)?/.test(th_class);
		
		if(th_class&&th_class.indexOf("formatter")>=0){
			var th_class_array = th_class.split(" ");
			var fn = "";
			for(var i=0;i<th_class_array.length;i++){
				if(th_class_array[i].indexOf("formatter")>=0){
					fn = th_class_array[i].substring(10,th_class_array[i].length);
					break;
				}
			}
			
			$("#"+tableId+" tbody tr:not(.grid_tr_templete)").each(function(i, d){
				var cell = $("td:eq("+index+")", d);
				var data = $.data(d,"record");
				
				if(fn && fn!="" && data){
					eval("("+fn+"(cell, data)"+")");
				}
			});
		}
	});
}
var formatter2 = function(tableId){
	var currentPageIndex = parseInt($("#"+tableId).currentPage());
	var pageSize = parseInt($("input.pageSize",$("[data-target-grid='"+tableId+"'] table ")).val());
	//格式化功能实现
	$("#"+tableId+" thead tr th").each(function(index, dom){
		var th_class = $(this).attr("class");
		//var result = /(.*\\s)?[fF][oO][rR][mM][aA][tT][tT][eE][rR]-.+(\\s.*)?/.test(th_class);
		
		if(th_class&&th_class.indexOf("formatter")>=0){
			var th_class_array = th_class.split(" ");
			var fn = "";
			for(var i=0;i<th_class_array.length;i++){
				if(th_class_array[i].indexOf("formatter")>=0){
					fn = th_class_array[i].substring(10,th_class_array[i].length);
					break;
				}
			}
			
			$("[data-target-grid='"+tableId+"'] tbody tr").each(function(i, d){
				var cell = $("td:eq("+index+")",d);
				var data = $.data(d,"record");
				
				if(fn && fn!="" && data){
					eval("("+fn+"(cell, data)"+")");
				}
			});
		}
	});
}


var pagebar = function(tableId){
	var pagebar = $("div.pagebar",$("#"+tableId));
	
	var params=$("#"+tableId).data("mobileGrid");
	$(".firstPage",pagebar).bind("click",function(){
		params=$("#"+tableId).data("mobileGrid");
		params.currentPageIndex=1;
//		$("#"+tableId).search({'currentPageIndex':1});
		$("#"+tableId).search(params);
		$("select.currentPage",pagebar).selectpicker("val",params.currentPageIndex);
	});
	$(".previousPage",pagebar).bind("click",function(){
		var span_currentPageIndex = $(".currentPageIndex",$("#"+tableId));
		var currentPageIndex = parseInt($(span_currentPageIndex).html());
		params=$("#"+tableId).data("mobileGrid");
		params.currentPageIndex=currentPageIndex>1?(currentPageIndex-1):1;
//		$("#"+tableId).search({'currentPageIndex':(currentPageIndex>1?(currentPageIndex-1):1)});
		$("#"+tableId).search(params);
		$("select.currentPage",pagebar).selectpicker("val",params.currentPageIndex);
	});
	$(".nextPage",pagebar).bind("click",function(){
		var span_currentPageIndex = $(".currentPageIndex",$("#"+tableId));
		var currentPageIndex = parseInt($(span_currentPageIndex).html());
		var span_totalPage = $(".totalPage",$("#"+tableId));
		var totalPage = parseInt($(span_totalPage).html());
		params=$("#"+tableId).data("mobileGrid");
		params.currentPageIndex=currentPageIndex<totalPage?(currentPageIndex+1):totalPage;
//		$("#"+tableId).search({'currentPageIndex':(currentPageIndex<totalPage?(currentPageIndex+1):totalPage)});
		$("#"+tableId).search(params);
		$("select.currentPage",pagebar).selectpicker("val",params.currentPageIndex);
	});
	$(".lastPage",pagebar).bind("click",function(){
		var span_totalPage = $(".totalPage",$("#"+tableId));
		var totalPage = parseInt($(span_totalPage).html());
		params=$("#"+tableId).data("mobileGrid");
		params.currentPageIndex=totalPage;
//		$("#"+tableId).search({'currentPageIndex':totalPage});
		$("#"+tableId).search(params);
		$("select.currentPage",pagebar).selectpicker("val",params.currentPageIndex);
	});
	$(".currentPage",pagebar).bind("change",function(){
		var span_totalPage = $(".totalPage",$("#"+tableId));
		var totalPage = parseInt($(span_totalPage).html());
		var input = $(".currentPage",$("#"+tableId));
		var currentPageIndex = parseInt($(input).val());
		params=$("#"+tableId).data("mobileGrid");
		params.currentPageIndex=currentPageIndex>totalPage?totalPage:(currentPageIndex<1?1:currentPageIndex);
//		$("#"+tableId).search({'currentPageIndex':currentPageIndex>totalPage?totalPage:(currentPageIndex<1?1:currentPageIndex)});
		$("#"+tableId).search(params);
	});
}


var pagebar2 = function(tableId){
	var pagebar = $("div.pagebar",$("[data-target-grid='"+tableId+"']"));
	
	$(".nextPage",pagebar).bind("click",function(){
		var nextBtn=$(this);
		params=$("#"+tableId).data("mobileGrid");
		var span_currentPageIndex = $("span.currentPageIndex",$("[data-target-grid='"+tableId+"']"));
		var currentPageIndex = parseInt($(span_currentPageIndex).html());
		var span_totalPage = $("span.totalPage",$("[data-target-grid='"+tableId+"']"));
		var totalPage = parseInt($(span_totalPage).html());
		params.currentPageIndex=currentPageIndex<totalPage?(currentPageIndex+1):totalPage;
		if(params.currentPageIndex==totalPage){
			
//			$(".nextPage",pagebar).html("没有更多数据了");
			$(".nextPage",pagebar).parents("tr:first").hide();
			if($("[data-target-grid='"+tableId+"']").attr('data-role')=="pullToRefresh"){
			     $("#pullUp",$("[data-target-grid='"+tableId+"']")).hide();	
				 
			}
		}
		if(nextBtn.is(":enabled")){
		   $("#"+tableId).search(params);
			if($("[data-target-grid='"+tableId+"']").attr('data-role')=="pullToRefresh"){
			     $("[data-target-grid='"+tableId+"']").pullToRefresh("refresh",500);	
				 
			}
			else{
		         $("[data-target-grid='"+tableId+"']").scrollview("refresh",500);	
			}
		}
	});
	
}
var showProgressBar = function(tableId){
	var loadingElement = document.getElementById(tableId+"_loading");
	if(loadingElement==null){
		$("#"+tableId).before("<div id='"+tableId+"_loading' style='display:none;'>/div>");
	}
	$.mobile.showPageLoadingMsg( "d", "正在加载中...", true );

						
	
}

var hideProgressBar = function(tableId){
	var loadingElement = document.getElementById(tableId+"_loading");
	if(loadingElement!=null){
		$.mobile.hidePageLoadingMsg();
	}
}


var createGridShowPatch=function(tableId,options){
	               
				var tableCss=$("#"+tableId).attr("class");
				$("[data-target-grid='"+tableId+"'] table").addClass(tableCss+" ui-mobile-grid ");
				var theadGrid=$("#"+tableId+" thead").clone();
				$("[data-target-grid='"+tableId+"'] table").append(theadGrid);
				$("[data-target-grid='"+tableId+"'] table thead").hide();
				$("div.pagebar.auto-pagebar",$("[data-target-grid='"+tableId+"'] table")).append(gridOptions.gridlistBarTempl);	
				if($("[data-target-grid='"+tableId+"']").attr('data-role')=="pullToRefresh"){
//					var htmlStr=' <div id="pullUp">'+
//	                     ' <div class="message">'+
//	                     ' <div class="pullUpIcon"></div><span class="pullLabel"></span>'+
//	                     ' </div>'+
//	                     ' </div>';
//						$("[data-target-grid='"+tableId+"'] .scroller").append(htmlStr);
						$("[data-target-grid='"+tableId+"']").attr("pullUpAction","loadMore");
						$("[data-target-grid='"+tableId+"']").pullToRefresh("reloadEvent",{onScrollEnd:function(){
							$("#"+tableId).loadNextPage();	 
						}})
					    $("[data-target-grid='"+tableId+"'] table tfoot td").hide();
					  
				};
				
			
			
};




})(jQuery);